// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: "test-2oth4"
})
const db = cloud.database();
const _ = db.command;


// 云函数入口函数
exports.main = async (event, context) => {
  //获取日期
  let timestamp = Date.parse(new Date());

  let myDate = new Date(timestamp);
  let day = myDate.getDate();
  let month = myDate.getMonth();
  month++
  let year = myDate.getFullYear();
  let hour = myDate.getHours();
  let minu = myDate.getMinutes();
  if (month < 10) { month = "0" + month; }
  if (day < 10) { day = "0" + day; }
  if (hour < 10) { hour = "0" + hour; }
  if (minu < 10) { minu = "0" + minu; }
  let time = year + '-' + month + '-' + day + ' ' + hour + ':' + minu;
  try {
    const messages = await db.collection('notepads').where({
      state: false,
      reminde: time
    }).get();

    const sendPromises = messages.data.map(async message => {
      try {
        await cloud.openapi.subscribeMessage.send({
          touser: message._openid,//推送的用户
          page: 'pages/schedule/schedule',//跳转的页面
          data: {
            thing1: {
              value: message.title?message.title:'无标题'
            },
            thing4: {
              value: message.center
            }
          },
          templateId: 'GchwxG9wH3_F0wiVy9IP1lP7l8aqr1ViKyMnXIwcbag'//模板ID
        })

        return db.collection('message').doc(message._id).update({
          data: {
            state: true,
          }
        })
      } catch (err) {
        return err
      }
    });
    return Promise.all(sendPromises);
  } catch (err) {
    return err
  }
}